package com.sky.controller.user;


import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "C端-用户相关接口") // swagger接口文档
@Slf4j //log 日志对象
@RestController // 标识是一个请求处理类
@RequestMapping("/user/user") //映射路径, 抽取
public class UserController {

    @Autowired
    private JwtProperties jwtProperties;

    //依赖注入
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param dto
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    //虽然--UserLoginDTO只有一个属性, 但是也是很有必要的
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO dto) {
        //1.关键入口, 输出日志
        log.info("开始登录--------------------");
        log.info("用户登录的授权码:dto={}", dto);
        //2.调用service的登录方法, 获取结果
        User user = userService.login(dto);
        //3.如果登录成功, 生成令牌jwt
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);


        //4.构造UerLoginVO对象, 并返回Result
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }

//    //测试用户端的拦截器
//    @GetMapping("/test")
//    public Result test(){
//        return Result.success();
//    }
}
